<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card class="box-card">
			<el-row>
				<el-col :span="6">
					<el-input placeholder="请输入内容" v-model="pageInfo.querys" clearable @clear="getMgByPage">
						<el-button slot="append" @click="getMgByPage" icon="el-icon-search"></el-button>
					</el-input>
				</el-col>
				<el-col :span="2" class="addUser">
					<el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
				</el-col>
			</el-row>
			<el-table :data="userList" border stripe style="width: 100%">
				<el-table-column prop="username" label="姓名">
				</el-table-column>
				<el-table-column prop="email" label="邮箱">
				</el-table-column>
				<el-table-column prop="mobile" label="电话">
				</el-table-column>
				<el-table-column prop="role_name" label="角色">
				</el-table-column>
				<el-table-column prop="mg_state" label="状态">
					<!--插槽  ，用于父元素向子元素传参
			template  括住的为子组件
			table  里面的数据为父组件数据
			table把每一行的数据对应的传递给scope
			如果你想使用数据可以通过scope.row获取对应行的数据
			-->
					<template slot-scope="scope">
						<el-switch v-model="scope.row.mg_state" @change="setMgState(scope.row)">
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column prop="address" label="操作" width="180px">
					<template slot-scope="scope">
						<el-tooltip class="item" effect="dark" content="编辑用户" placement="top">
							<el-button type="primary" size="mini" icon="el-icon-edit"
								@click="showeditUserDialog(scope.row)"></el-button>
						</el-tooltip>
						<el-tooltip class="item" effect="dark" content="删除用户" placement="top">
							<el-button type="danger" size="mini" icon="el-icon-delete"
								@click="deleteUser(scope.row.id)"></el-button>
						</el-tooltip>
						<el-tooltip class="item" effect="dark" content="分配权限" placement="top">
							<el-button type="warning" size="mini" icon="el-icon-setting"
								@click="devideperm(scope.row )"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="pageInfo.pagenum" :page-sizes="[2,5,8,10]" :page-size="pageInfo.pagesize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-card>
		<!-- 添加用户弹出框 -->
		<el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="50%" @close="resetAddUserDialog"
			:before-close="handleClose">
			<el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addUserForm.username" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="userpwd">
					<el-input v-model="addUserForm.userpwd" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="useremail">
					<el-input v-model="addUserForm.useremail" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="usermobile">
					<el-input v-model="addUserForm.usermobile" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addUserDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addUser">确 定</el-button>
			</span>
		</el-dialog>
		<!--编辑用户-->
		<el-dialog title="编辑用户" :visible.sync="editUserDialogVisible" width="50%" @close="resetEditUserDialog">
			<el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserForm">
				<el-form-item label="用户名">
					<el-input v-model="editUserForm.username" disabled></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="useremail">
					<el-input v-model="editUserForm.useremail"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="usermobile">
					<el-input v-model="editUserForm.usermobile"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editUserDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editUser(editUserForm.userId)">确 定</el-button>
			</span>
		</el-dialog>
		<!--分配权限-->
		<el-dialog title="分配权限" :visible.sync="deviPermDialogVisible" width="50%" @close="ClearSelect">
			<div>
				<p>当前的用户:   {{userName}}</p>
				<p>当前的角色:   {{roleName}}</p>
				<p>
					分配新角色:
					<el-select v-model="setRoleId" placeholder="请选择">
						<el-option v-for="item in roleList" :key="item.role_id" :label="item.role_name" :value="item.role_id">
							
						</el-option>
					</el-select>
				</p>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="deviPermDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="allocationPerm">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			let checkEmial = (rule, value, cb) => {
				const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
				if (regEmail.test(value)) {
					return cb();
				}
				return cb('请输入合法的邮箱')
			}
			let checkMobile = (rule, value, cb) => {
				const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
				if (regMobile.test(value)) {
					return cb();
				}
				return cb('请输入合法的电话号码')
			}
			return {
				userList: [],
				pageInfo: {
					querys: '',
					pagenum: 1,
					pagesize: 2
				},
				total: '',
				addUserDialogVisible: false, //控制添加用户弹出框是
				addUserForm: {
					username: '',
					userpwd: '',
					useremail: '',
					usermobile: ''
				},
				addUserFormRules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 10,
							message: '长度在 3 到 10 个字符',
							trigger: 'blur'
						}
					],
					userpwd: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 15,
							message: '长度在 6 到 15 个字符',
							trigger: 'blur'
						}
					],
					useremail: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmial,
							trigger: 'blur'
						}
					],
					usermobile: [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				},
				editUserFormRules: {
					useremail: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmial,
							trigger: 'blur'
						}
					],
					usermobile: [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				},
				editUserDialogVisible: false,
				editUserForm: {
					userId: '',
					username: '',
					useremail: '',
					usermobile: ''
				},
				deviPermDialogVisible:false,//控制分配权限对话框是否隐藏
				setRoleId:'',//角色id
				roleList:[],//所有的角色
				userName:'',
				roleName:'',
				userId:''
			}
		},
		methods: {
			async getMgByPage() {
				let {
					data: res
				} = await this.$http.get('/manager/users', {
					params: this.pageInfo
				})
				console.log(res);
				if (res.meta.status !== 200) return this.$message.error('用户列表获取失败')
				this.userList = res.data.users;
				this.total = res.data.totalCount
				this.pageInfo.pagenum = res.data.pagenum;
			},
			handleSizeChange(newSize) {
				this.pageInfo.pagesize = newSize;
				this.getMgByPage()
			},
			handleCurrentChange(newpage) {
				this.pageInfo.pagenum = newpage;
				this.getMgByPage()
			},
			resetAddUserDialog() {
				//重置表单
				this.$refs.addUserForm.resetFields();
			},
			addUser() {
				//添加用户
				//预验证
				this.$refs.addUserForm.validate(async valid => {
					if (!valid) return;
					let {
						data: res
					} = await this.$http.post('/manager/users', this.addUserForm);
					if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
					if (res.meta.status == 200) this.$message.success(res.meta.msg)
					this.getMgByPage();
					this.addUserDialogVisible = false;
				})
			},
			async setMgState(mgInfo) {
				//put 请求 这是restFul编码风格，目前的主流风格，请求方式不能像以前一样
				//要么get 要么post.restFul风格要求增删改查用不同的请求方式
				//增 post  删  delete  改 put 查 get/post  登陆必须用post
				let {
					data: res
				} = await this.$http.put(`/manager/users/${mgInfo.id}/state/${mgInfo.mg_state}`)
				if (res.meta.status !== 200) {
					mgInfo.mg_state = !mgInfo.mg_state
					return this.$message.error(res.meta.msg)
				}
				this.$message.success(res.meta.msg)
			},
			resetEditUserDialog() {
				this.$refs.editUserForm.resetFields();
			},
			showeditUserDialog(userInfo) {
				this.editUserForm.username = userInfo.username;
				this.editUserForm.useremail = userInfo.email;
				this.editUserForm.usermobile = userInfo.mobile;
				this.editUserForm.userId = userInfo.id;
				this.editUserDialogVisible = true;
			},
			editUser(id) {
				this.$refs.editUserForm.validate(async valid => {
					if (!valid) return;
					let {
						data: res
					} = await this.$http.put(`/manager/users/${id}`, this.editUserForm)
					if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
					this.$message.success(res.meta.msg)
					this.getMgByPage();
					this.editUserDialogVisible = false;
				})
			},
			async deleteUser(uid) {
				let resultConfirm = await this.$confirm(
					'此操作将永久删除该用户, 是否继续?',
					'提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}
				).catch(error => error)
				if (resultConfirm !== 'confirm') {
					return this.$message.info('操作已取消')
				}
				let {
					data: res
				} = await this.$http.delete(`/manager/users/${uid}`);
				if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
				this.$message.success(res.meta.msg);
				this.getMgByPage()
			},
			async devideperm(mgInfo){
				//展示分配权限对话框的方法
				this.userName = mgInfo.username;
				this.roleName = mgInfo.role_name;
				this.userId = mgInfo.id;
				let {data: res} = await this.$http.get('/role/roles');
				if(res.meta.status !== 200) return this.$message.error('角色列表获取失败')
				this.roleList  = res.data;
				this.deviPermDialogVisible = true;
			},
			ClearSelect(){
				this.setRoleId = '',
				this.roleList = []
			},
			async allocationPerm(){
				//完成角色分配
				let {data: res} = await this.$http.put(`/manager/users/${this.userId}/role/${this.setRoleId}`)
				if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
				this.$message.success(res.meta.msg)
				this.getMgByPage()
				this.deviPermDialogVisible = false;
			}
		},
		created() {
			this.getMgByPage()
		}
	}
</script>
<style lang="scss">
	.addUser {
		margin-left: 15px;
	}
</style>
